﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

using YouErYuanModels;
using YouErYuanBLL;
using CommonLib;

namespace YouErYuanManage.Filter
{
    /// <summary>
    /// 全局异常捕获过滤器
    /// </summary>
    public class logExceptionAttribute : HandleErrorAttribute
    {
        ErrorLogBLL logbll = new ErrorLogBLL();

        public override void OnException(ExceptionContext filterContext)
        {
            //如果异常没有被处理，则进入if块进行处理
            if (filterContext.ExceptionHandled == false)
            {
                string controllerName = (string)filterContext.RouteData.Values["controller"];
                string actionName = (string)filterContext.RouteData.Values["action"];
                bool isAjax = filterContext.HttpContext.Request.IsAjaxRequest();

                Exception ex = filterContext.Exception;
                string msg = ex.Message;

                //查找出错代码行号
                int index1 = ex.StackTrace.IndexOf("行号");
                string className = "";
                string lineNo = "";
                string address = "";
                if (index1 != -1)
                {
                    string xiabanTxt = ex.StackTrace.Substring(index1, 20);//行号后面的字符串
                    int zaiIndex2 = index1 + xiabanTxt.IndexOf("\r\n");//继行号\r\n的下标
                    int len = zaiIndex2 - index1 - 3;
                    lineNo = ex.StackTrace.Substring(index1 + 3, len);//出错行号
                                                                      //查找类名
                    int wezhi = ex.StackTrace.IndexOf("位置") + 3;
                    int endindex = index1 - 1;
                    int length = endindex - wezhi;
                    string filePath = ex.StackTrace.Substring(wezhi, length);
                    className = System.IO.Path.GetFileName(filePath);//出错最开始的类名

                    address = string.Format("异常类名{0}，行号{1}", className, lineNo);
                }
                else
                {
                    address = "控制器" + controllerName + "，方法" + actionName;
                }
                if (isAjax)
                {
                    ContentResult result = new ContentResult();
                    string msgTxt = address + "，消息：" + msg;
                    //编码消息
                    byte[] bytes = Encoding.UTF8.GetBytes(msgTxt);
                    string bmMsg = Convert.ToBase64String(bytes);
                    string jsonTxt = CommonMethod.FormatJsonObj("500", bmMsg);
                    result.Content = jsonTxt;
                    filterContext.Result = result;
                }
                else
                {
                    ViewResult result = new ViewResult();
                    result.ViewName = "Error";
                    result.ViewBag.address = address;
                    result.ViewBag.info = msg;
                    result.ViewBag.stack = ex.StackTrace;
                    filterContext.Result = result;
                }
                //记录日志
                ManageErrorLog log = new ManageErrorLog();
                log.Id = Guid.NewGuid().ToString();
                log.Classname = className;
                log.Lineno = lineNo;
                log.Errormsg = msg;
                logbll.AddErrorLog(log);

                filterContext.ExceptionHandled = true;//设置异常已处理
            }
        }
    }
}
